#version 420

layout(lines_adjacency) in;
layout(triangle_strip, max_vertices = 4) out;

uniform mat4 ModelViewMatrix;
uniform mat4 NormalViewMatrix;
uniform mat4 ProjectionMatrix;
uniform mat4 ModelViewProjectionMatrix;
uniform vec3 VolumeSize;
uniform float LengthThreshold;

out vec3 pos;
out vec3 norm;
out vec3 texCoord;

const float radius = 1.0 / length(VolumeSize);

void main()
{
    if(LengthThreshold > gl_in[1].gl_Position.w)
    {
        return;
    }

    for(int i = 0; i < 2; i++)
    {
        //vec3 c0 = gl_in[i].gl_Position.xyz;
        vec3 p = (ModelViewMatrix * vec4(gl_in[i+1].gl_Position.xyz, 1.0)).xyz;
        vec3 c = (ModelViewMatrix * vec4(gl_in[i+2].gl_Position.xyz, 1.0)).xyz;

        // current plan normal
        vec3 t = c - p;

        // view to p direction
        vec3 u = vec3(0.0, 0.0, -1.0);

        // uper axis
        vec3 axisY = normalize(cross(t, u));

        // loacal silhouette vector e
        vec3 e = radius * axisY;

        pos = p;
        norm = axisY;
        texCoord = gl_in[i+1].gl_Position.xyz / VolumeSize;
        gl_Position = ProjectionMatrix * vec4(p + e, 1.0);
        EmitVertex();

        pos = p;
        norm = -axisY;
        texCoord = gl_in[i+1].gl_Position.xyz / VolumeSize;
        gl_Position = ProjectionMatrix * vec4(p - e, 1.0);
        EmitVertex();
    }

    EndPrimitive();
}
